package com.fanfanwang.ffw.app.net;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;

import com.fanfanwang.ffw.app.common.LogUtil;
/**
 * 访问Web Service的工具类
 * @author jCuckoo
 * 
 */
/**
 * @author Administrator
 *
 */
/**
 * @author Administrator
 *
 */
@SuppressLint("NewApi")
public class WebServiceHelper {
	
	public static String URL = "http://182.92.173.95:82/api/index.php/?wsdl";
	public static String BaseUrl = "http://182.92.173.95:82/api/";
	public static String url_users = "users.php";
	public static String url_parking = "parking.php";
	public static String url_system = "system.php";
	
	
	
	public static final String apiusernamekey = "apiusername";
	public static final String apiusernamevalue = "huoer";
	public static final String apipasswordkey = "apipassword";
	/**登录*/
	public static final String _LOGIN = "login";
	/**i.	Reg用户注册*/
	public static final String _REG = "reg";
	/**ii.	isreg用户检测*/
	public static final String _ISREG = "isreg";
	/**iii.	ichksms验证短信验证码*/
	public static final String _CHKSMS = "chksms";
	/**iv.	updateMobile修改用户手机号*/
	public static final String _UPDATEMOBILE = "updateMobile";
	/**v.	updateUserinfo修改用户基本资料*/
	public static final String _UPDATEUSERINFO = "updateUserinfo";
	/**vi.	getUserInfo获取用户基本资料*/
	public static final String _GETUSERINFO = "getUserInfo";
	/**vii.	setPassword修改用户密码*/
	public static final String _SETPASSWORD = "setPassword";
	/**viii.	setNewPassword设置用户新密码*/
	public static final String _SETNEWPASSWORD = "setNewPassword";
	/**ix.	saveFeedback用户意见反馈*/
	public static final String _SAVEFEEDBACK = "saveFeedback";
	/**viii.	isregReturn 用户找回密码验证码发送*/
	public static final String _ISREGRETURN = "isregReturn";
	
	
	//parking.php
	/**i.	getparkingList获取当前位置停车场数组*/
	public static final String _GETPARKINGLIST = "getparkingList";
	/**ii.	getCityList获取区域列表*/
	public static final String _GETCITYLIST = "getCityList";
	/**iii.	getLengthList获取搜索距离数组*/
	public static final String _GETLENGTHLIST = "getLengthList";
	/**iv.	getParkList获取指定路段停车场列表*/
	public static final String _GETPARKLIST = "getParkList";
	/**v.	getParkingInfo获取指定停车场详细信息*/
	public static final String _GETPARKINGINFO = "getParkingInfo";
	/**vi.	getDianList获取洗车店、4S店、加油站列表*/
	public static final String _GETDIANLIST = "getDianList";
	/**vii.	order_done预约停车位*/
	public static final String _ORDER_DONE = "saveOrder";
	/**viii.	getNewsList获取汽车资讯列表*/
	public static final String _GETNEWSLIST = "getNewsList";
	/**ix.	getNewsInfo获取汽车资讯详细信息*/
	public static final String _GETNEWSINFO = "getNewsInfo";
	
	//查看预约记录
	/**i.	getOrdersList获取预约记录*/
	public static final String _GETORDERSLIST = "getOrdersList";
	/**ii.	getOrdersInfo获取预约记录详情*/
	public static final String _GETORDERSINFO = "getOrdersInfo";
	/**viii.	getYuyueList获取用户有效预约记录	*/
	public static final String _GETYUYUELIST = "getYuyueList";
	
	
	/********************************* 系统基础函数*******************/
	/**ii.	getAppVersion获取手机版本信息*/
	public static final String _GETAPPVERSION = "getAppVersion";

	
	
	public static String httpXieYiString="http://www.fenfenriji.com/help/term_mob.html";
	
	static String NAMESPACE = "http://182.92.173.95:82";// 名称空间，服务器端生成的namespace属性值
	static {
		if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH){
			// 4.0以后需要加入下列两行代码，才可以访问Web Service
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.detectDiskReads().detectDiskWrites().detectNetwork()
					.penaltyLog().build());

			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
					.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
					.penaltyLog().penaltyDeath().build());
		}
		//4.0以前版本不需要以上设置
	}
	public static boolean isIOException = true;
	/**
	 * @param url          web service路径
	 * @param nameSpace    web service名称空间
	 * @param methodName   web service方法名称
	 * @param params       web service方法参数
	 */
	public static SoapObject getSoapObject(String url,String methodName, String soapAction, HashMap<String, Object> params) {
		String METHOD_NAME = methodName;
		String SOAP_ACTION = soapAction;
		SoapObject soap = null;
		//如果请求不成功则循环请求
		boolean isSucceed = false;
		int index = 0;
		while(!isSucceed && index <3){
			try {
				//实例化SoapObject对象。
				SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);
				if (params != null && params.size() > 0) {
					for (Entry<String, Object> item : params.entrySet()) {
						//如果有参数的话，设置调用参数
						rpc.addProperty(item.getKey(), item.getValue().toString());
					}
				}
				//设置soap请求信息（参数部分为soap协议版本号 ，与要调用的webservice中版本号一致）
				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				envelope.bodyOut = rpc;
				envelope.dotNet = false;// true--net; false--php  java;
				envelope.setOutputSoapObject(rpc);
//				构建传输对象，并指明WSDL文档URL
				HttpTransportSE ht = new HttpTransportSE(BaseUrl + url);
				ht.debug = true;
				//调用WebService(其中参数为1：命名空间+方法名称，2：Envelope对象)
				String soap_action1=NAMESPACE+METHOD_NAME;
				ht.call(SOAP_ACTION, envelope);
				try {
					soap = (SoapObject) envelope.getResponse();
				} catch (Exception e) {
					LogUtil.e("WebServiceHelper", "getSoapObject",e.getMessage());
					soap = (SoapObject) envelope.bodyIn;
				}
				isSucceed = true;
			} catch (IOException ex) {
				ex.printStackTrace();
				
				LogUtil.e("WebServiceHelper", "IOException   ex  >> ", ex.getMessage());
				if(!TextUtils.isEmpty(ex.getMessage()) && ex.getMessage().equals("BufferedInputStream is closed")){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					getSoapObject(url, methodName, soapAction, params);
					isSucceed = false;
				}else {
					isSucceed = true;
				}
			} catch (Exception ex) {
				ex.printStackTrace();
				
				LogUtil.e("WebServiceHelper", "Exception   ex  >> ", ex.getMessage());
			}
			index ++;
			LogUtil.e("WebServiceHelper", "getSoapObject   >> " + soap,"   isSucceed  >> " + isSucceed);
		}
		return soap;
	}
}
